<?php
//decode by QQ:270656184 http://www.yunlu99.com/
defined('IN_IA') or exit('Access Denied');
define('OB_ROOT', IA_ROOT . '/attachment/bsht_tbk');

class Bsht_tbkModule extends WeModule
{
	public $tableset = 'bsht_tbk_set';
	public $tablereply = 'bsht_tbk_poster';

	public function fieldsFormDisplay($rid = 0)
	{
		load()->func('tpl');
		global $_W;
		if (!empty($rid)) {
			$item = pdo_fetch("SELECT * FROM " . tablename($this->tablereply) . " WHERE rid = :rid ORDER BY `id` DESC", array(':rid' => $rid));
		}
		if ($item) {
			$data = json_decode(str_replace('&quot;', "'", $item['data']), true);
			$size = getimagesize(toimage($item['bg']));
			$size = array($size[0] / 2, $size[1] / 2);
			$date = array('start' => date('Y-m-d H:i:s', $item['starttime']), 'end' => date('Y-m-d H:i:s', $item['endtime']));
		}
		$groups = pdo_fetchall('select * from ' . tablename('mc_groups') . " where uniacid='{$_W['uniacid']}' order by isdefault desc");
		include $this->template('reply');
	}

	public function fieldsFormSubmit($rid)
	{
		global $_GPC, $_W;
		$key = str_replace('[', "", $_GPC['keywords']);
		$key = str_replace(']', "", $key);
		$key = str_replace('&quot;', '"', $key);
		$keywords = json_decode($key, true);
		$id = intval($_GPC['reply_id']);
		$insert = array('rid' => $rid, 'uniacid' => $_W['uniacid'], 'rtype' => $_GPC ['rtype'], 'title' => $_GPC ['title'], 'type' => $_GPC ['type'], 'data' => htmlspecialchars_decode($_GPC ['data']), 'bg' => $_GPC ['bg'], 'score' => $_GPC ['score'], 'fscore' => $_GPC ['fscore'], 'cscore' => $_GPC ['cscore'], 'pscore' => $_GPC ['pscore'], 'rscore' => $_GPC ['rscore'], 'gid' => $_GPC ['gid'], 'qrtype' => $_GPC ['qrtype'], 'addinfo1' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['addinfo1']), ENT_QUOTES), 'addinfo2' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['addinfo2']), ENT_QUOTES), 'addinfo3' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['addinfo3']), ENT_QUOTES), 'rtips' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['rtips']), ENT_QUOTES), 'ftips' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['ftips']), ENT_QUOTES), 'utips' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['utips']), ENT_QUOTES), 'utips2' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['utips2']), ENT_QUOTES), 'nostarttxt' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['nostarttxt']), ENT_QUOTES), 'endtxt' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['endtxt']), ENT_QUOTES), 'starttime' => strtotime($_GPC['starttime']), 'endtime' => strtotime($_GPC['endtime']), 'surl' => serialize($_GPC ['surl']), 'credit' => $_GPC ['credit'], 'mbcolor' => $_GPC ['mbcolor'], 'mbstyle' => $_GPC ['mbstyle'], 'mbfont' => $_GPC ['mbfont'], 'tzurl' => $_GPC ['tzurl'], 'createtime' => time(),);
		if (empty($id)) {
			$id = pdo_insert($this->tablereply, $insert);
			$rid1 = pdo_insertid();
			$rule = array('uniacid' => $_W['uniacid'], 'name' => '确认好友(请勿修改本项设置)', 'module' => $this->modulename, 'status' => 1, 'displayorder' => 255,);
			$rule2 = array('uniacid' => $_W['uniacid'], 'name' => 'NB文字签到', 'module' => $this->modulename, 'status' => 1, 'displayorder' => 255,);
			pdo_insert('rule', $rule2);
			$rid2 = pdo_insertid();
			unset($rule2['name']);
			$rule2['type'] = 1;
			$rule2['rid'] = pdo_insertid();
			$rule2['content'] = 'NB文字签到';
			pdo_insert('rule_keyword', $rule2);
			pdo_update($this->tablereply, array('rid2' => $rid2), array('id' => $rid1));
			message('保存成功', 'refresh');
		} else {
			unset($insert['createtime']);
			pdo_update($this->tablereply, $insert, array('id' => $id));
			pdo_update('qrcode', array('keyword' => $keywords['content'], 'name' => $_GPC ['title']), array('uniacid' => $_W['uniacid']));
			message('修改成功', 'refresh');
		}
	}

	public function ruleDeleted($rid)
	{
		global $_W;
		pdo_delete($this->tablereply, array('rid' => $rid));
		$name = pdo_fetch('select title from ' . tablename($this->modulename . "_poster") . " where rid='{$rid}'");
		pdo_delete('qrcode', array('name' => $name['title'], 'uniacid' => $_W['uniacid']));
	}

	public function settingsDisplay($settings)
	{
		global $_W, $_GPC;
		load()->model('attachment');
		$infotip = "<div class='main'><div class='panel panel-default'><div class='panel-heading'>规则说明</div><div class='panel-body'>　　用户第一天签到，就赠送“首次签到积分”，然后连续每天签到都将递增“续签递增积分”，如果中断，将重新回到“首次签到积分”，然后再重新递增<br>　　例如：首次签到积分为10；续签递增积分为2<br>　　那么用户第一天签到赠送10个积分，第二天12个积分，第三天14个积分 （10+12+14+16+18+20……）<br>　　如果有设上限，例如上限是20，就是（10+12+14+16+18+20+20+20+20+20+20+20……）<br>　　但是如果有一天没签到（中断了）那么下次签到又从10分送起<br>　　好处：增加用户对公众号的粘性（该奖励积分不和上下级关系形成互动）</div></div></div>";
		if (checksubmit()) {
			$remote = array('type' => intval($_GPC['type']), 'ftp' => array('ssl' => intval($_GPC['ftp']['ssl']), 'host' => $_GPC['ftp']['host'], 'port' => $_GPC['ftp']['port'], 'username' => $_GPC['ftp']['username'], 'password' => strexists($_GPC['ftp']['password'], '*') ? $_W['setting']['remote']['ftp']['password'] : $_GPC['ftp']['password'], 'pasv' => intval($_GPC['ftp']['pasv']), 'dir' => $_GPC['ftp']['dir'], 'url' => $_GPC['ftp']['url'], 'overtime' => intval($_GPC['ftp']['overtime']),), 'alioss' => array('key' => $_GPC['alioss']['key'], 'secret' => strexists($_GPC['alioss']['secret'], '*') ? $_W['setting']['remote']['alioss']['secret'] : $_GPC['alioss']['secret'], 'bucket' => $_GPC['alioss']['bucket'],), 'qiniu' => array('accesskey' => trim($_GPC['qiniu']['accesskey']), 'secretkey' => strexists($_GPC['qiniu']['secretkey'], '*') ? $_W['setting']['remote']['qiniu']['secretkey'] : trim($_GPC['qiniu']['secretkey']), 'bucket' => trim($_GPC['qiniu']['bucket']), 'district' => intval($_GPC['qiniu']['district']), 'url' => trim($_GPC['qiniu']['url'])), 'cos' => array('appid' => trim($_GPC['cos']['appid']), 'secretid' => trim($_GPC['cos']['secretid']), 'secretkey' => strexists(trim($_GPC['cos']['secretkey']), '*') ? $_W['setting']['remote']['cos']['secretkey'] : trim($_GPC['cos']['secretkey']), 'bucket' => trim($_GPC['cos']['bucket']), 'url' => trim($_GPC['cos']['url'])));
			if ($remote['type'] == ATTACH_OSS) {
				if (trim($remote['alioss']['key']) == '') {
					message('阿里云OSS-Access Key ID不能为空');
				}
				if (trim($remote['alioss']['secret']) == '') {
					message('阿里云OSS-Access Key Secret不能为空');
				}
				$buckets = attachment_alioss_buctkets($remote['alioss']['key'], $remote['alioss']['secret']);
				if (is_error($buckets)) {
					message('OSS-Access Key ID 或 OSS-Access Key Secret错误，请重新填写');
				}
				list($remote['alioss']['bucket'], $remote['alioss']['url']) = explode('@@', $_GPC['alioss']['bucket']);
				if (empty($buckets[$remote['alioss']['bucket']])) {
					message('Bucket不存在或是已经被删除');
				}
				$remote['alioss']['url'] = 'http://' . $remote['alioss']['bucket'] . '.' . $buckets[$remote['alioss']['bucket']]['location'] . '.aliyuncs.com';
				$remote['alioss']['ossurl'] = $buckets[$remote['alioss']['bucket']]['location'] . '.aliyuncs.com';
				if (!empty($_GPC['custom']['url'])) {
					$url = trim($_GPC['custom']['url'], '/');
					if (!strexists($url, 'http://') && !strexists($url, 'https://')) {
						$url = 'http://' . $url;
					}
					$remote['alioss']['url'] = $url;
				}
			} elseif ($remote['type'] == ATTACH_FTP) {
				if (empty($remote['ftp']['host'])) {
					message('FTP服务器地址为必填项.');
				}
				if (empty($remote['ftp']['username'])) {
					message('FTP帐号为必填项.');
				}
				if (empty($remote['ftp']['password'])) {
					message('FTP密码为必填项.');
				}
			} elseif ($remote['type'] == ATTACH_QINIU) {
				if (empty($remote['qiniu']['accesskey'])) {
					message('请填写Accesskey', referer(), 'info');
				}
				if (empty($remote['qiniu']['secretkey'])) {
					message('secretkey', referer(), 'info');
				}
				if (empty($remote['qiniu']['bucket'])) {
					message('请填写bucket', referer(), 'info');
				}
				if (empty($remote['qiniu']['url'])) {
					message('请填写url', referer(), 'info');
				} else {
					$remote['qiniu']['url'] = strexists($remote['qiniu']['url'], 'http') ? trim($remote['qiniu']['url'], '/') : 'http://' . trim($remote['qiniu']['url'], '/');
				}
				$auth = attachment_qiniu_auth($remote['qiniu']['accesskey'], $remote['qiniu']['secretkey'], $remote['qiniu']['bucket'], $remote['qiniu']['district']);
				if (is_error($auth)) {
					$message = $auth['message']['error'] == 'bad token' ? 'Accesskey或Secretkey填写错误， 请检查后重新提交' : 'bucket填写错误或是bucket所对应的存储区域选择错误，请检查后重新提交';
					message($message, referer(), 'info');
				}
			} elseif ($remote['type'] == ATTACH_COS) {
				if (empty($remote['cos']['appid'])) {
					message('请填写APPID', referer(), 'info');
				}
				if (empty($remote['cos']['secretid'])) {
					message('请填写SECRETID', referer(), 'info');
				}
				if (empty($remote['cos']['secretkey'])) {
					message('请填写SECRETKEY', referer(), 'info');
				}
				if (empty($remote['cos']['bucket'])) {
					message('请填写BUCKET', referer(), 'info');
				}
				if (empty($remote['cos']['url'])) {
					$remote['cos']['url'] = 'http://' . $remote['cos']['bucket'] . '-' . $remote['cos']['appid'] . '.cos.myqcloud.com';
				} else {
					if (strexists($remote['cos']['url'], '.cos.myqcloud.com') && !strexists($url, '//' . $remote['cos']['bucket'] . '-')) {
						$remote['cos']['url'] = 'http://' . $remote['cos']['bucket'] . '-' . $remote['cos']['appid'] . '.cos.myqcloud.com';
					}
					$remote['cos']['url'] = strexists($remote['cos']['url'], 'http') ? trim($remote['cos']['url'], '/') : 'http://' . trim($remote['cos']['url'], '/');
				}
				$auth = attachment_cos_auth($remote['cos']['bucket'], $remote['cos']['appid'], $remote['cos']['secretid'], $remote['cos']['secretkey']);
				if (is_error($auth)) {
					message($auth['message'], referer(), 'info');
				}
			}
			$dat = array('sd_msname' => $_GPC['sd_msname'], 'sd_mshead' => $_GPC['sd_mshead'], 'sd_msfoot' => $_GPC['sd_msfoot'], 'sd_msdo' => $_GPC['sd_msdo'], 'sd_msmain' => $_GPC['sd_msmain'], 'certkey' => $_GPC['certkey'], 'tencent_lbs_api_key' => $_GPC['tencent_lbs_api_key'], 'isopenweixin' => $_GPC['isopenweixin'], 'key' => $_GPC['key'], 'mchid' => $_GPC['mchid'], 'apikey' => $_GPC['apikey'], 'remote' => $remote, 'appkey' => $_GPC['appkey'], 'appsecret' => $_GPC['appsecret'], 'switch' => $_GPC['switch'], 'isposter' => $_GPC['isposter'], 'bsht_tbk_fansnum' => $_GPC['bsht_tbk_fansnum'], 'bsht_tbk_usr' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['bsht_tbk_usr']), ENT_QUOTES), 'bsht_tbk_diyurl1' => $_GPC['bsht_tbk_diyurl1'], 'bsht_tbk_diyurl2' => $_GPC['bsht_tbk_diyurl2'], 'bsht_tbk_diyurl3' => $_GPC['bsht_tbk_diyurl3'], 'hbsctime' => $_GPC['hbsctime'], 'hbcsmsg' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['hbcsmsg']), ENT_QUOTES), 'hbyanshi' => $_GPC['hbyanshi'], 'bill_bg' => $_GPC['bill_bg'], 'bill_hint' => $_GPC['bill_hint'], 'bill_dec' => $_GPC['bill_dec'], 'bill_data' => htmlspecialchars_decode($_GPC['bill_data']), 'paihangs' => intval($_GPC['paihangs']), 'px' => intval($_GPC['px']), 'paihangt' => intval($_GPC['paihangt']), 'ispaihang' => intval($_GPC['ispaihang']), 'welcome' => trim($_GPC['welcome']), 'time' => $_GPC['time'], 'intup' => intval($_GPC['intup']), 'continuity' => intval($_GPC['continuity']), 'everyday' => intval($_GPC['everyday']), 'success_msg' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['success_msg']), ENT_QUOTES), 'continuity_msg' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['continuity_msg']), ENT_QUOTES), 'nbqd_diy' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['nbqd_diy']), ENT_QUOTES), 'nbqd_diyurl1' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['nbqd_diyurl1']), ENT_QUOTES), 'nbqd_diyurl2' => htmlspecialchars_decode(str_replace('&quot;', '&#039;', $_GPC ['nbqd_diyurl2']), ENT_QUOTES), 'isalldiy' => $_GPC['isalldiy'], 'urldiy_b1' => $_GPC['urldiy_b1'], 'urldiy_b2' => $_GPC['urldiy_b2'], 'urldiy_b3' => $_GPC['urldiy_b3'], 'urldiy_b4' => $_GPC['urldiy_b4'], 'urldiy_b11' => $_GPC['urldiy_b11'], 'urldiy_b22' => $_GPC['urldiy_b22'], 'urldiy_b33' => $_GPC['urldiy_b33'], 'urldiy_b44' => $_GPC['urldiy_b44'],);
			$this->saveSettings($dat);
			message('保存成功', 'refresh');
		}
		if (!file_exists(MODULE_ROOT . "/res/font/font.ttf")) {
			$nofont = 1;
		}
		$settings = $this->module['config'];
		$bill_data = json_decode(str_replace('&quot;', "'", $settings['bill_data']), true);
		$remote = $settings['remote'];
		if (!empty($remote['alioss']['key']) && !empty($remote['alioss']['secret'])) {
			$buckets = attachment_alioss_buctkets($remote['alioss']['key'], $remote['alioss']['secret']);
		}
		$bucket_datacenter = attachment_alioss_datacenters();
		include $this->template('remote');
	}

	public function createRandomStr($length)
	{
		$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$strlen = 26;
		while ($length > $strlen) {
			$str .= $str;
			$strlen += 26;
		}
		$str = str_shuffle($str);
		return substr($str, 0, $length);
	}
}